package com.yb.bussiness.shoper;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.yb.base.dao.BaseDao;
import com.yb.base.dao.IBaseDao;
import com.yb.domain.goods.ShoperMessage;
import com.yb.util.comm.DateTimeUtil;
import com.yb.util.framework.PageUtil;

public class ShoperMessageServiceImpl implements ShoperMessageService {

	private IBaseDao<ShoperMessage, Long> messageDao;
	private static final Logger LOGGER = Logger
			.getLogger(ShoperMessageServiceImpl.class);

	public ShoperMessageServiceImpl() {
		messageDao = new BaseDao<ShoperMessage, Long>(ShoperMessage.class);
	}

	public boolean isSaveOrUpdate(ShoperMessage shopMessage) {
		try {
			messageDao.saveOrUpdate(shopMessage);
			return true;
		} catch (Exception e) {
			LOGGER.error("ShoperMessageServiceImpl  saveOrUpdate error", e);
			return false;
		}

	}

	public List<ShoperMessage> findByParameMap(Map<String, String> parameMap) {
		try {
			String str = " SELECT  * FROM shopmessager  where 1=1 ";
			if (parameMap.get("autding") != null) {
				str += " and autding = " + parameMap.get("autding");
			}
			if (parameMap.get("shoperId") != null) {
				str += " and shoperId = " + parameMap.get("shoperId");
			}
			if (parameMap.get("page") != null && parameMap.get("row") != null) {
				int start = Integer.parseInt(parameMap.get("page")) - 1;
				int limit = Integer.parseInt(parameMap.get("row"));
				str += " limit " + start * limit + "," + limit;
			}
			List<ShoperMessage> list = messageDao.findList(str);
			if (list != null && !list.isEmpty()) {
				List<ShoperMessage> newlist = new ArrayList<ShoperMessage>();
				for (ShoperMessage shoperMessage : list) {
					shoperMessage.setCreatTimeStr(DateTimeUtil
							.switchDateToString(shoperMessage.getCreatime(),
									"yyyy-MM-dd HH:mm:ss"));
					newlist.add(shoperMessage);
				}
				return newlist;
			}
		} catch (Exception e) {
			LOGGER.error(" ShoperMessageServiceImpl findByParameMap error", e);
			;
			return null;
		}
		return null;
	}

	public int searchByCount(Map<String, String> parameMap) {
		int count = 0;
		try {
			String str = "  SELECT  count(*) FROM shopmessager m  LEFT JOIN  t_g_brand t  ON  m.shoperId=t.id where 1=1   ";
			if (parameMap.get("brandid") != null
					&& !"".equals(parameMap.get("brandid"))) {
				str += "  and t.id = " + parameMap.get("brandid");
			}
			if (parameMap.get("title") != null
					&& !"".equals(parameMap.get("title"))) {
				str += "  and title LIKE   '%" + parameMap.get("title") + "%'";
			}
			if (parameMap.get("name") != null
                && !"".equals(parameMap.get("name"))) {
            str += "  and name LIKE   '%" + parameMap.get("name") + "%'";
        }
			if (parameMap.get("auding") != null
					&& !"".equals(parameMap.get("auding"))) {
				str += " and autding = " + parameMap.get("auding");
			}
			if (parameMap.get("shoperId") != null) {
				str += " and shoperId = " + parameMap.get("shoperId");
			}
			if ("1".equals(parameMap.get("userType"))||"0".equals(parameMap.get("userType"))) {
				str += " and (deleteFlag IS NULL OR deleteFlag=0) ";
			}
			List<Object[]> list = messageDao.findObjectArryList(str);
			if (list != null) {
				Object[] objAry = list.get(0);
				count = new Integer(objAry[0].toString());
			}
		} catch (Exception e) {
			LOGGER.error(" ShoperMessageServiceImpl  count error", e);
			return 0;
		}
		return count;
	}

	public List<ShoperMessage> searchByParameMap(Map<String, String> parameMap) {
		try {
			String str = " SELECT  m.id AS id ,m.title AS title,m.content AS content,m.creatime AS creatime,m.shoperId AS shoperId ,m.autding AS autding ,t.name AS descrt,m.recommend,m.isTop,m.deleteFlag FROM shopmessager m ,  t_g_brand t  where  m.shoperId=t.id ";
			if (parameMap.get("brandid") != null
					&& !"".equals(parameMap.get("brandid"))) {
				str += "  and t.id = " + parameMap.get("brandid");
			}

			if (parameMap.get("title") != null
					&& !"".equals(parameMap.get("title"))) {
				str += "  and title LIKE   '%" + parameMap.get("title") + "%'";
			}
			if (parameMap.get("name") != null
                && !"".equals(parameMap.get("name"))) {
            str += "  and name LIKE   '%" + parameMap.get("name") + "%'";
        }
			if (parameMap.get("auding") != null
					&& !"".equals(parameMap.get("auding"))) {
				str += " and autding = " + parameMap.get("auding");
			}
			if (parameMap.get("shoperId") != null) {
				str += " and shoperId = " + parameMap.get("shoperId");
			}

			if ("1".equals(parameMap.get("userType"))||"0".equals(parameMap.get("userType"))) {
				str += " and (deleteFlag IS NULL OR deleteFlag=0) ";
			}

			if (parameMap.get("page") != null && parameMap.get("row") != null) {
				int start = Integer.parseInt(parameMap.get("page")) - 1;
				int limit = Integer.parseInt(parameMap.get("row"));
				str += " limit " + start * limit + "," + limit;
			}
			List<ShoperMessage> list = messageDao.findList(str);
			// 糟糕的代码
			if (list != null && !list.isEmpty()) {
				List<ShoperMessage> newlist = new ArrayList<ShoperMessage>();
				for (ShoperMessage shoperMessage : list) {
					shoperMessage.setCreatTimeStr(DateTimeUtil
							.switchDateToString(shoperMessage.getCreatime(),
									"yyyy-MM-dd HH:mm:ss"));
					newlist.add(shoperMessage);
				}
				return newlist;
			}
		} catch (Exception e) {
			LOGGER
					.error(" ShoperMessageServiceImpl searchByParameMap error",
							e);
			;
			return null;
		}
		return null;
	}

	public boolean deleteById(String ids, String userType) {
		boolean isFlag = true;
		if ("".equals(ids))
			return false;
		String sql = "";
		String[] delteid = ids.split("_");
		try {
			for (int i = 0; i < delteid.length; i++) {
				if ("1".equals(userType)||"0".equals(userType)) {
					sql = "UPDATE shopmessager set deleteFlag = 1 where id="
							+ delteid[i];
					messageDao.update(sql);
				} else {
					sql = "delete  from shopmessager where id=" + delteid[i];
					messageDao.delete(sql);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error(" ShoperMessageServiceImpl deleteById   error", e);
			return false;
		}
		return isFlag;
	}

	public boolean updateAutingId(String id, String autding) {
		try {
			String sql = " UPDATE  shopmessager t set t.autding=" + autding
					+ " WHERE t.id= " + id;
			messageDao.update(sql);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error(" ShoperMessageServiceImpl updateAutingId   error", e);
			return false;
		}

	}

	public int count(Map<String, String> parameMap) {
		try {
			String str = "  SELECT  * FROM shopmessager where 1=1 ";
			if (parameMap.get("brandid") != null
					&& !"".equals(parameMap.get("brandid"))) {
				str += "  and id = " + parameMap.get("brandid");
			}

			if (parameMap.get("title") != null
					&& !"".equals(parameMap.get("title"))) {
				str += "  and title LIKE   '%" + parameMap.get("title") + "%'";
			}
			if (parameMap.get("auding") != null
					&& !"".equals(parameMap.get("auding"))) {
				str += " and autding = " + parameMap.get("autding");
			}
			if (parameMap.get("shoperId") != null) {
				str += " and shoperId = " + parameMap.get("shoperId");
			}
			List<ShoperMessage> list = messageDao.findList(str);
			if (list != null) {
				return list.size();
			}
		} catch (Exception e) {
			LOGGER.error(" ShoperMessageServiceImpl  count error", e);
			return 0;
		}
		return 0;
	}

	public ShoperMessage findById(String id) {
		String str = " SELECT  * FROM shopmessager  WHERE id =? ";
		try {
			List<ShoperMessage> list = messageDao.findList(str,
					new Object[] { id });
			if (list != null && !list.isEmpty()) {
				return list.get(0);
			}
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error(
					" ShoperMessageServiceImpl  findById " + id + " error", e);
			return null;
		}

		return null;
	}

	public PageUtil findMessageByBrandId(Long brandId, int page, int limit) {
		String sql = "SELECT  * FROM shopmessager  where autding='1' and shoperId = ? and (isTop <> '1' or isTop is null) and (recommend <> '1' or recommend is null) AND (deleteFlag IS NULL OR deleteFlag=0)";
		List<ShoperMessage> list = messageDao.findList(sql,
				new Object[] { brandId });
		PageUtil pu = new PageUtil();
		int start = (page - 1) * limit;
		if (null != list) {
			pu.setTotalRecords(list.size());
			if (-1 != page)
				list = list.subList((start > 0 ? start : 0),
						(list.size() < ((start > 0 ? start : 0) + limit) ? list
								.size() : ((start > 0 ? start : 0) + limit)));
			pu.setList(list);
		} else {
			pu.setTotalRecords(0);
			pu.setList(new ArrayList<ShoperMessage>());
		}
		pu.setPageNo(page);
		pu.setPageSize(limit);
		return pu;
	}

	public List<ShoperMessage> findMessage3ByBrandId(Long brandId) {
		String sql = "SELECT  * FROM shopmessager  where autding='1' and shoperId = ? and isTop = '1' and recommend = '1' AND (deleteFlag IS NULL OR deleteFlag=0)";
		List<ShoperMessage> list = messageDao.findList(sql,
				new Object[] { brandId });
		return list;
	}

	public List<ShoperMessage> findMessage2ByBrandId(Long brandId) {
		String sql = "SELECT  * FROM shopmessager  where autding='1' and shoperId = ? and (isTop <> '1' or isTop is null) and recommend = '1' AND (deleteFlag IS NULL OR deleteFlag=0)";
		List<ShoperMessage> list = messageDao.findList(sql,
				new Object[] { brandId });
		return list;
	}

	public List<ShoperMessage> findMessage1ByBrandId(Long brandId) {
		String sql = "SELECT  * FROM shopmessager  where autding='1' and shoperId = ? and isTop = '1' and (recommend <> '1' or recommend is null) AND (deleteFlag IS NULL OR deleteFlag=0)";
		List<ShoperMessage> list = messageDao.findList(sql,
				new Object[] { brandId });
		return list;
	}

	public PageUtil findMessageCommendList(int page, int limit) {
		PageUtil pu = new PageUtil();
		pu.setPageNo(page);
		pu.setPageSize(limit);
		String sql = "SELECT sm.id,sm.title,gg.name descrt,sm.creatime,tgb.realName content FROM t_r_messageCommend tmc, shopmessager sm,t_g_brand tgb,t_g_brand gg WHERE sm.shoperId = gg.id AND tmc.messageId = sm.id AND tgb.sysuserId = tmc.userId  ORDER BY sm.creatime DESC limit ?,?";
		String countSql = "select count(*) FROM t_r_messageCommend tmc, shopmessager sm,t_g_brand tgb,t_g_brand gg WHERE sm.shoperId = gg.id AND tmc.messageId = sm.id AND tgb.sysuserId = tmc.userId";
		List<Object[]> countList = messageDao.findObjectArryList(countSql);
		if (null != countList && countList.size() > 0) {
			Object[] countAry = countList.get(0);
			pu.setTotalRecords(new Integer(countAry[0].toString()));
		} else {
			pu.setTotalRecords(0);
		}
		List<ShoperMessage> list = messageDao.findList(sql, new Object[] {
				(page - 1) * limit, limit });
		pu.setList(list);
		return pu;
	}

	public boolean changeIsTopById(String id, String isTop) {
		try {
			if ("".equals(id))
				return false;
			String sql = "update shopmessager set isTop=? where id=? ";
			messageDao.update(sql, new Object[] { id, isTop });
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	public boolean changeTopByIdString(String idString, String isTop) {
		boolean isFlag = true;
		if (idString == null || "".equals(idString))
			return false;
		String sql = "";
		String[] delteid = idString.split("_");
		try {
			for (int i = 0; i < delteid.length; i++) {
				sql = "update shopmessager set isTop=" + isTop + " where id="
						+ delteid[i];
				messageDao.update(sql);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return isFlag;
	}

}
